package dao;

import pojo.Commodity;
import sql.BaseUtil;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class CommodityDao extends BaseUtil {
    public int Add(Commodity commodity){
        String sql = "insert into commodity (id,name,data,expirationData,manufacturer,price)values(?,?,?,?,?,?)";
        Object [] obj = {commodity.getId(),commodity.getName(),commodity.getData(),commodity.getExpirationData(),commodity.getManufacturer(),commodity.getPrice()};
        int update = this.setUpdate(sql, obj);
        return update;
    }
    public List Show() throws Exception {

        String sql = "select * from commodity";
        Object [] obj = {};
        ResultSet select = this.select(sql, obj);
        List<Commodity> list = new ArrayList<>();
        while (select.next()){
            Commodity b = new Commodity();
            b.setId(select.getInt(1));
            b.setName(select.getString(2));
            b.setData(select.getString(3));
            b.setExpirationData(select.getString(4));
            b.setManufacturer(select.getString(5));
            b.setPrice(select.getInt(6));
            list.add(b);
        }
        return list ;
    }
    public int Delete(String name){
        String sql = "delete from commodity where name = ?";
        Object [] obj = {name};
        int update = this.setUpdate(sql, obj);
        return update;
    }
    public Commodity Select(String name){
        String sql = "select *  from commodity where name = ?";
        Object [] obj = {name};
        Commodity b = null;
        try {
            ResultSet select = this.select(sql, obj);
            while (select.next()){
                b = new Commodity();
                b.setId(select.getInt(1));
                b.setName(select.getString(2));
                b.setData(select.getString(3));
                b.setExpirationData(select.getString(4));
                b.setManufacturer(select.getString(5));
                b.setPrice(select.getInt(6));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return b;
    }

    public int Borrow(String name){
        String sql = "update commodity set isBorrowed = 0 where name = ?";
        Object [] obj = {name};
        int update = this.setUpdate(sql, obj);
        return update;
    }

    public int Return(String name){
        String sql = "update commodity set isBorrowed = 1 where name = ?";
        Object [] obj = {name};
        int update = this.setUpdate(sql, obj);
        return update;
    }
}
